package com.qys.livesMall.navy.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.common.exception.enums.ExceptionEnum;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.navy.common.Constant;
import com.qys.livesMall.navy.mapper.H2NavyLanguageManageMapper;
import com.qys.livesMall.navy.model.dto.task.AddVideoComment;
import com.qys.livesMall.navy.model.entity.H2NavyLanguageManage;
import com.qys.livesMall.navy.model.entity.NavyTask;
import com.qys.livesMall.navy.model.entity.NavyTaskDetail;
import com.qys.livesMall.navy.service.NavyTaskDetailService;
import com.qys.livesMall.navy.service.NavyTaskService;
import com.qys.livesMall.navy.service.NavyVideoCommentService;
import com.qys.livesMall.navy.task.TaskInter;
import com.qys.livesMall.shortVideo.model.dto.app.AppUserCommentDTO;
import com.qys.livesMall.shortVideo.service.IH2ShortVideoCommentsService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class NavyVideoCommentServiceImpl implements NavyVideoCommentService {

    @Resource
    private MessageServer messageServer;

    @Resource
    private NavyTaskService navyTaskService;

    @Resource
    private NavyTaskDetailService navyTaskDetailService;

    @Resource
    private IH2ShortVideoCommentsService ih2ShortVideoCommentsService;

    @Resource
    private H2NavyLanguageManageMapper h2NavyLanguageManageMapper;

    @Resource
    @Lazy
    private TaskInter taskInter;

    @Override
    public R buildTask(AddVideoComment param) {
        if (param == null || CollectionUtils.isEmpty(param.getUserIds()) || CollectionUtils.isEmpty(param.getVideoIds())) {
            return messageServer.failMsg(ExceptionEnum.PARAM_IS_ERROR);
        }
        NavyTask navyTask = new NavyTask();
        navyTask.setTaskType(Constant.TaskType.VIDEO_COMMENT);
        navyTask.setTaskName("短视频评论");
        navyTask.setTaskParam(JSONObject.toJSONString(param));
        navyTask.setTaskStatus(Constant.TaskStatus.RUNNING);
        navyTask.setTaskStartTime(LocalDateTime.now());
        navyTask.setCreateDate(LocalDateTime.now());
        navyTask.setUpdDate(LocalDateTime.now());
        navyTaskService.save(navyTask);
        //创建任务明细
        List<NavyTaskDetail> detailList = new ArrayList<>();
        for (int i = 0; i < param.getUserIds().size(); i++) {
            NavyTaskDetail detail = new NavyTaskDetail();
            detail.setTaskId(navyTask.getId());
            detail.setTaskType(navyTask.getTaskType());
            detail.setSort(i + 1);
            detail.setNavyIds(JSONObject.toJSONString(Collections.singletonList(param.getUserIds().get(i))));
            detail.setVideoIds(JSONObject.toJSONString(param.getVideoIds()));
            detail.setCreateDate(LocalDateTime.now());
            detail.setTaskStatus(Constant.TaskDetailStatus.NO_START);
            detailList.add(detail);
        }
        navyTaskDetailService.batchSave(detailList);
        //启动
        for (NavyTaskDetail navyTaskDetail:detailList){
            exc(navyTaskDetail.getId());
        }
        return R.ok();
    }

    @Override
    @Async
    public void exc(Long taskDetailId) {
        NavyTaskDetail detail = navyTaskDetailService.getById(taskDetailId);
        if (detail == null) {
            return;
        }
        List<String> videoIds = JSONArray.parseArray(detail.getVideoIds()).toList(String.class);
        String userId = JSONArray.parseArray(detail.getNavyIds()).get(0).toString();

        try {
//            根据短视频数量随机查询短视频评论
            LambdaQueryWrapper<H2NavyLanguageManage> query = Wrappers.lambdaQuery(H2NavyLanguageManage.class);
//          水军语言类型（0：水军弹幕 1：水军商品评论 2：水军短视频评论）
            query.eq(H2NavyLanguageManage::getType, 2)
                    .last(" ORDER BY RAND() ")
                    .last(" LIMIT " + videoIds.size());

            List<H2NavyLanguageManage> h2NavyLanguageManages = h2NavyLanguageManageMapper.selectList(query);

            for (int i = 0; i < videoIds.size(); i++) {
                H2NavyLanguageManage languageManage;
                if (i >= h2NavyLanguageManages.size()) {
                    languageManage = h2NavyLanguageManages.get(h2NavyLanguageManages.size()-1);
                }else{
                    languageManage = h2NavyLanguageManages.get(i);
                }
                AppUserCommentDTO appUserCommentDTO = new AppUserCommentDTO();
                appUserCommentDTO.setVideoId(videoIds.get(i));
                appUserCommentDTO.setUserId(userId);
                if (languageManage != null) {
                    appUserCommentDTO.setComment(languageManage.getContent());
                }
                ih2ShortVideoCommentsService.comment(appUserCommentDTO);
            }
        } catch (Exception e) {
            detail.setTaskStatus(Constant.TaskDetailStatus.END_FAIL);
            detail.setTaskDate(LocalDateTime.now());
            navyTaskDetailService.upById(detail);
            return;
        }

        detail.setTaskStatus(Constant.TaskDetailStatus.END_SUCCESS);
        navyTaskDetailService.upById(detail);
        //同步主任务状态
        boolean end = navyTaskService.watchTaskEnd(detail.getTaskId());
        if (end) {
            return;
        }
        //获取下一个任务
        NavyTaskDetail nextDetail = navyTaskDetailService.getNextDetail(detail.getTaskId());
        if (nextDetail != null) {
            taskInter.addVideoCommentTask(RandomUtil.randomInt(600, 5400), nextDetail.getId());
        }
    }
}
